package com.kaifamiao.servlet;

import com.kaifamiao.entity.Customer;
import com.kaifamiao.jdbc.helper.JdbcHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/customer/edit/action")
public class CustomerEditActionServlet extends HttpServlet {

    private JdbcHelper helper;
    private String update;

    @Override
    public void init() throws ServletException {
        helper = JdbcHelper.getInstance();
        update = "UPDATE t_customers SET username = ? , nickname = ? WHERE id = ? ";
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置编码
        request.setCharacterEncoding( "UTF-8" );
        response.setCharacterEncoding("UTF-8");
        // 设置MIME类型
        response.setContentType("text/html; charset=UTF-8");
        // 获得向响应缓冲区输出数据的字符打印流
        PrintWriter out = response.getWriter();
        // 链接外部样式文件
        out.println( "<link rel=\"stylesheet\" href=\"/css/customer.css\">");
        String uname = request.getParameter( "username" );
        String nickname = request.getParameter( "nickname" );
        String idString = request.getParameter( "id" );
        Integer id = Integer.valueOf( idString );

        try {
            int count = helper.execute(update, uname, nickname, id);
            if (count == 1) {
                out.println("<p>修改成功</p>");
            } else {
                out.println("<p>修改失败</p>");
            }
        } catch ( Exception e ) {
            out.println("<p>修改失败</p>");
            e.printStackTrace();
        }

        out.println( "<p> <a href=\"/customer/list\">返回列表</a></p>" );
    }

    @Override
    public void destroy() {
        helper.release();
    }

}
